package com.lovo.rb.service;

import com.alibaba.fastjson2.JSON;
import com.lovo.dto.UserDto;
import com.lovo.rb.dao.IUserDao;
import com.lovo.rb.entity.UserEntity;
import com.lovo.util.ConvertBeanUtil;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl {
    @Autowired
    private IUserDao userDao;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    RabbitTemplate.ConfirmCallback callback=(CorrelationData correlationData, boolean b, String s)->{
        if(b){
            //投递成功才保存
          String json=  correlationData.getId();
            System.out.println(json);
        }
    };
    //发送用户信息到MQ,同时持久化数据，如果发生MQ失败就删除数据
    public boolean saveAndSendMQ(UserEntity user) throws InterruptedException {
        rabbitTemplate.setMandatory(true);//开启confirm确认机制
        rabbitTemplate.setConfirmCallback(callback);//绑定回调函数
         //把user转换为json
        String userJSON= JSON.toJSONString(user);
        //发送MQ
      CorrelationData correlationData=new CorrelationData();
      correlationData.setId(userJSON);
        UserDto userDto;
       userDto= ConvertBeanUtil.copy(user,UserDto.class);
      rabbitTemplate.convertAndSend("directExchangeOne","movie.ticket",userDto,correlationData);
        Thread.sleep(300);
          return true;
    }
}
